package com.gree.manager.interceptor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.gree.commom.utils.CookieUtil;
import com.gree.commom.utils.JsonUtil;
import com.gree.sso.entity.Admin;
import com.gree.sso.service.SSOService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 后台登录拦截器
 * @author zhoubin
 * @since 1.0.0
 */
@Component
public class ManagerLoginInterceptor implements HandlerInterceptor {

    @Reference(interfaceClass = SSOService.class)
    private SSOService ssoService;

    @Value("${user.ticket}")
    private String userTicket;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户名票据
        String ticket = CookieUtil.getCookieValue(request, "userTicket");
        if (!StringUtils.isEmpty(ticket)) {
            //如果票据存在，进行验证
            Admin admin = ssoService.validate(ticket);
            //将用户信息添加至session中，用于页面返显
            request.getSession().setAttribute("user", admin);
            //重新设置新的失效时间
            redisTemplate.opsForValue().set(userTicket + ":" + ticket, JsonUtil.object2JsonStr(admin), 30, TimeUnit.MINUTES);
            return true;
        }
        //票据不存在或者用户验证失败，重定向至登录页面
        response.sendRedirect(request.getContextPath() + "/login");
        return false;
    }

}
